package com.lmf.eduservice.controller;


import com.lmf.eduservice.client.VodClient;
import com.lmf.eduservice.entity.EduVideo;
import com.lmf.eduservice.service.EduVideoService;
import com.lmf.handler.Exception.LmfException;
import com.lmf.resultCode.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author lmf
 * @since 2022-01-25
 */
@Api(description = "小节管理")
@CrossOrigin
@RestController
@RequestMapping("/eduservice/edu-video")
public class EduVideoController {

    @Autowired
    private EduVideoService eduVideoService;
    @Autowired
    private VodClient vodClient;    //将远程调用接口注入过来

    @ApiOperation("添加小节")
    @PostMapping("/addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo){
        eduVideoService.save(eduVideo);
        return R.ok();
    }

    @ApiOperation("根据id，修改小节")
    @PostMapping("/updateVideo")
    public R updateVideo(@RequestBody EduVideo eduVideo){
        eduVideoService.updateById(eduVideo);
        return R.ok();
    }

    @ApiOperation("根据id，删除小节")
    @DeleteMapping("/deleteVideo/{videoId}")
    public R removeVideo(@PathVariable("videoId") String videoId) throws LmfException {
        //1.根据小节id，查询视频的存储在阿里云上面的真实id
        EduVideo eduVideo = eduVideoService.getById(videoId);
        String videoSourceId = eduVideo.getVideoSourceId();
        if (!videoSourceId.isEmpty()) {
            //2.删除阿里云上面的视频
            R result = vodClient.deleteVideoById(videoSourceId);
            if (result.getCode() == 20001) {
                throw new LmfException(20001,"删除视频失败");
            }
        }
        //3.删除小节
        eduVideoService.removeById(videoId);
        return R.ok();
    }

    @ApiOperation("根据id，查找小节")
    @GetMapping("/getVideoById/{videoId}")
    public R getVideoById(@PathVariable("videoId") String videoId){
        EduVideo eduVideo = eduVideoService.getById(videoId);
        return R.ok().data("video",eduVideo);
    }
}

